package com.app.base.simples.list.tree.provider;

import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;

import com.app.base.R;
import com.app.base.simples.list.tree.DefaultTreeAdapter;
import com.app.base.simples.list.tree.bean.SecondNode;
import com.chad.library.adapter.base.entity.node.BaseNode;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.zndroid.base.binder.AbsProvider;

import java.util.Objects;

public class SecondProvider extends AbsProvider<DefaultTreeAdapter> {

    @Override
    public int getItemViewType() {
        return 2;
    }

    @Override
    public int getLayoutId() {
        return R.layout.item_node_second;
    }

    @Override
    public void convert(@NonNull BaseViewHolder helper, @NonNull BaseNode data) {
        SecondNode entity = (SecondNode) data;
        helper.setText(R.id.title, entity.getTitle());
        helper.setText(R.id.num, Objects.requireNonNull("id= " + ((SecondNode) data).getId()));

        if (getAdapter().isSelectEnable()) {
            helper.getView(R.id.cb).setVisibility(View.VISIBLE);
        } else {
            helper.getView(R.id.cb).setVisibility(View.GONE);
        }

        CheckBox checkBox = helper.getView(R.id.cb);
        checkBox.setChecked(entity.isChecked());
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (buttonView.isPressed()) {
                    getAdapter().toSelectItem(data, isChecked);
                }
            }
        });

        ImageView imageView = helper.getView(R.id.iv);

        if (!getAdapter().isNotEmpty(data.getChildNode())) {
            imageView.setVisibility(View.INVISIBLE);
            return;
        }

        imageView.setVisibility(View.VISIBLE);

        if (entity.isExpanded()) {
            ViewCompat.animate(imageView).setDuration(200)
                    .setInterpolator(new DecelerateInterpolator())
                    .rotation(90f)
                    .start();
        } else {
            ViewCompat.animate(imageView).setDuration(200)
                    .setInterpolator(new DecelerateInterpolator())
                    .rotation(0f)
                    .start();
        }
    }

    @Override
    public void onClick(@NonNull BaseViewHolder helper, @NonNull View view, BaseNode data, int position) {
        SecondNode entity = (SecondNode) data;
        if (entity.isExpanded()) {
            getAdapter().collapse(position, true);
        } else {
            getAdapter().expandAndCollapseOther(position);
        }
    }
}
